


package ciicos.check.controller;

import ciicos.base.ActionResult;
import ciicos.base.UserInfo;
import ciicos.base.vo.PageListVO;
import ciicos.base.vo.PaginationVO;
import ciicos.check.entity.CheckItemsEntity;
import ciicos.check.entity.CheckPlanEntity;
import ciicos.check.entity.CheckPlanItemEntity;
import ciicos.check.entity.CheckPlanTimeEntity;
import ciicos.check.entity.CheckTaskEntity;
import ciicos.check.model.checkplan.CheckPlanForm;
import ciicos.check.model.checkplan.CheckPlanInfoVO;
import ciicos.check.model.checkplan.CheckPlanItemModel;
import ciicos.check.model.checkplan.CheckPlanListVO;
import ciicos.check.model.checkplan.CheckPlanPagination;
import ciicos.check.model.checkplan.CheckPlanTimeModel;
import ciicos.check.service.CheckPlanItemService;
import ciicos.check.service.CheckPlanService;
import ciicos.check.service.CheckPlanTimeService;
import ciicos.check.service.CheckTaskService;
import ciicos.equ.entity.EquPointEntity;
import ciicos.exception.DataException;
import ciicos.permission.entity.UserEntity;
import ciicos.equ.service.EquBaseService;
import ciicos.equ.service.EquPointService;
import ciicos.util.DateUtil;
import ciicos.util.GeneraterSwapUtil;
import ciicos.util.JsonUtil;
import ciicos.util.RandomUtil;
import ciicos.util.StringUtil;
import ciicos.util.UserProvider;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 巡检计划
 *
 * @版本： V3.2.0
 * @版权：
 * @作者： 产研项目租
 * @日期： 2023-08-16
 */
@Slf4j
@RestController
@Api(tags = "巡检计划", value = "checkManage")
@RequestMapping("/api/checkManage/CheckPlan")
public class CheckPlanController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;


    @Autowired
    private UserProvider userProvider;

    @Autowired
    private CheckPlanService checkPlanService;

    @Autowired
    private CheckPlanItemService checkPlanItemService;
    @Autowired
    private CheckPlanTimeService checkPlanTimeService;

    /*
     *   通过设备id查询点位
     * */
    @ApiOperation(" 通过设备id查询点位")
    @GetMapping("/findPointByEquId/{equId}/{type}")
    public ActionResult findPointByEquId(@PathVariable("equId") String equId, @PathVariable("type") String type) {
        try {
            if ("1".equals(type)) {
                List<EquPointEntity> equPointEntities = checkPlanService.findPointByEquId(equId);
                if (equPointEntities.size() != 0) {
                    return ActionResult.success(equPointEntities);
                }
            } else {
                List<CheckItemsEntity> assetsChecksEntitys = checkPlanService.findDescById(equId);
                return ActionResult.success(assetsChecksEntitys);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ActionResult.success();
    }

    /**
     * 列表
     *
     * @param checkPlanPagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody CheckPlanPagination checkPlanPagination) throws IOException {
        //树形判断是否有参数，有参数不造树
        List<CheckPlanEntity> list = checkPlanService.getList(checkPlanPagination);
        //处理id字段转名称，若无需转或者为空可删除

        List<CheckPlanListVO> listVO = JsonUtil.getJsonToList(list, CheckPlanListVO.class);
        for (CheckPlanListVO checkPlanVO : listVO) {

            List<CheckPlanItemEntity> itemEntities = checkPlanItemService.list(new LambdaQueryWrapper<CheckPlanItemEntity>().eq(CheckPlanItemEntity::getParentid, checkPlanVO.getId()));
            List<CheckPlanTimeEntity> timeEntities = checkPlanTimeService.list(new LambdaQueryWrapper<CheckPlanTimeEntity>().eq(CheckPlanTimeEntity::getParentid, checkPlanVO.getId()));
            StringBuilder scheduled = new StringBuilder();
            for (CheckPlanTimeEntity timeEntity : timeEntities) {
                String timeType = timeEntity.getTimetype();
                timeType = generaterSwapUtil.getDicName(timeType, "509339643641104965");
                Integer timespaced = timeEntity.getTimespaced();
                scheduled.append(timespaced).append(timeType).append(" ");

            }
            checkPlanVO.setScheduled_name(scheduled.toString());

            checkPlanVO.setItemtotals_name(itemEntities.size() + "");
            checkPlanVO.setCreatoruserid_name(generaterSwapUtil.userSelectValue(checkPlanVO.getCreatoruserid()));

            SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = s.format(checkPlanVO.getCreatortime());
            checkPlanVO.setCreatortime_name(time);

            checkPlanVO.setLastmodifyuserid_name(generaterSwapUtil.userSelectValue(checkPlanVO.getLastmodifyuserid()));

            checkPlanVO.setLastmodifytime_name(checkPlanVO.getLastmodifytime());

            checkPlanVO.setCode_name(checkPlanVO.getCode());

            checkPlanVO.setName_name(checkPlanVO.getName());

            checkPlanVO.setNeeduser_name(checkPlanVO.getNeeduser());

            checkPlanVO.setNeedtime_name(checkPlanVO.getNeedtime());

            checkPlanVO.setErrormax_name(checkPlanVO.getErrormax());

            checkPlanVO.setErrormin_name(checkPlanVO.getErrormin());

            checkPlanVO.setCheckteam_name(generaterSwapUtil.comSelectValues(checkPlanVO.getCheckteam(), false));

            checkPlanVO.setEnabledmark_name(generaterSwapUtil.switchSelectValue(checkPlanVO.getEnabledmark(), "启用", "禁用"));

            checkPlanVO.setDescription_name(checkPlanVO.getDescription());

            checkPlanVO.setFiles_name(generaterSwapUtil.getFileNameInJson(checkPlanVO.getFiles()));

        }

        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(checkPlanPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param checkPlanForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid CheckPlanForm checkPlanForm) throws DataException {

        String b = checkPlanService.checkForm(checkPlanForm, 0);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        }

        if (checkPlanForm.getCheckplanitemList().size() == 0) {
            return ActionResult.fail("至少需要配置一条[巡检项]");

        }
        if (checkPlanForm.getCheckplantimeList().size() == 0) {
            return ActionResult.fail("至少需要配置一条[定时配置]");

        }
        String mainId = RandomUtil.uuId();

        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        checkPlanForm.setCreatoruserid(userInfo.getUserId());
        checkPlanForm.setCreatortime(DateUtil.getNow());
        checkPlanForm.setCode(generaterSwapUtil.getBillNumber("jhbm", false));
        CheckPlanEntity entity = JsonUtil.getJsonToBean(checkPlanForm, CheckPlanEntity.class);
        entity.setId(mainId);
        checkPlanService.save(entity);
        if (checkPlanForm.getCheckplanitemList() != null) {
            List<CheckPlanItemEntity> CheckPlanItemList = JsonUtil.getJsonToList(checkPlanForm.getCheckplanitemList(), CheckPlanItemEntity.class);
            for (CheckPlanItemEntity entitys : CheckPlanItemList) {
                entitys.setId(RandomUtil.uuId());
                entitys.setParentid(entity.getId());

                if (StringUtil.isNotEmpty(entitys.getCheckid())) {
                    entitys.setCheckid(JsonUtil.getJsonToList(entitys.getCheckid(), String.class).get(0));
                }
                checkPlanItemService.save(entitys);
            }
        }
        if (checkPlanForm.getCheckplantimeList() != null) {
            List<CheckPlanTimeEntity> CheckPlanTimeList = JsonUtil.getJsonToList(checkPlanForm.getCheckplantimeList(), CheckPlanTimeEntity.class);
            for (CheckPlanTimeEntity entitys : CheckPlanTimeList) {
                entitys.setId(RandomUtil.uuId());
                entitys.setParentid(entity.getId());

                checkPlanTimeService.save(entitys);
            }
        }


        return ActionResult.success("创建成功");
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<CheckPlanInfoVO> info(@PathVariable("id") String id) {
        CheckPlanEntity entity = checkPlanService.getInfo(id);
        CheckPlanInfoVO vo = JsonUtil.getJsonToBean(entity, CheckPlanInfoVO.class);
        vo.setCreatoruserid(generaterSwapUtil.userSelectValue(vo.getCreatoruserid()));
        if (vo.getCreatortime() != null) {
            vo.setCreatortime(vo.getCreatortime());
        }
        vo.setLastmodifyuserid(generaterSwapUtil.userSelectValue(vo.getLastmodifyuserid()));
        if (vo.getLastmodifytime() != null) {
            vo.setLastmodifytime(vo.getLastmodifytime());
        }

        //子表
        List<CheckPlanItemEntity> checkPlanItemList = checkPlanService.getCheckPlanItemList(id);
        for (CheckPlanItemEntity checkPlanItemEntity : checkPlanItemList) {
            //编码转名称
//            List<EquPointEntity> points = equPointService.list(new LambdaQueryWrapper<EquPointEntity>()
//                    .eq(EquPointEntity::getCode, checkPlanItemEntity.getPointName()));
//            if (points!=null&&points.size()!=0) {
//                checkPlanItemEntity.setPointName(points.get(0).getName());
//            }
        }
        vo.setCheckPlanItemList(JsonUtil.getJsonToList(checkPlanItemList, CheckPlanItemModel.class));

        List<CheckPlanTimeEntity> CheckPlanTimeList = checkPlanService.getCheckPlanTimeList(id);
        vo.setCheckPlanTimeList(JsonUtil.getJsonToList(CheckPlanTimeList, CheckPlanTimeModel.class));
        //副表
        return ActionResult.success(vo);
    }

    @Autowired
    private EquBaseService equBaseService;
    @Autowired
    private EquPointService equPointService;

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<CheckPlanInfoVO> detailInfo(@PathVariable("id") String id) {
        ActionResult info = info(id);
        Map<String, Object> dataMap = JsonUtil.entityToMap(info.getData());
        CheckPlanEntity entity = checkPlanService.getInfo(id);
        CheckPlanInfoVO vo = JsonUtil.getJsonToBean(entity, CheckPlanInfoVO.class);

        //子表数据转换
        List<CheckPlanItemEntity> checkPlanItemList = checkPlanService.getCheckPlanItemList(id);
        List<CheckPlanItemModel> checkPlanItemModelList = JsonUtil.getJsonToList(checkPlanItemList, CheckPlanItemModel.class);
        int checkPlanItemNum = 0;
        for (CheckPlanItemModel checkPlanItemModel : checkPlanItemModelList) {
            String type = checkPlanItemModel.getType();
            checkPlanItemModel.setType(generaterSwapUtil.getDicName(type, "529564962180304773"));
            Map<String, Object> checkPlanItemcheckidMap = new HashMap<>();
            if (StringUtil.isNotEmpty(checkPlanItemModel.getEquid())) {
                if ("1".equals(type)) {

                    checkPlanItemModel.setEquid(equBaseService.getInfo(checkPlanItemModel.getEquid()).getName());
                } else {
                    checkPlanItemModel.setEquid(generaterSwapUtil.getPopupSelectValue("529327550036447045", "F_Id", "F_Name", (String) checkPlanItemModel.getEquid(), checkPlanItemcheckidMap, "[]", checkPlanItemNum, dataMap));

                }
            }
            checkPlanItemNum++;
        }
        vo.setCheckPlanItemList(checkPlanItemModelList);
        List<CheckPlanTimeEntity> checkPlanTimeList = checkPlanService.getCheckPlanTimeList(id);
        List<CheckPlanTimeModel> checkPlanTimeModelList = JsonUtil.getJsonToList(checkPlanTimeList, CheckPlanTimeModel.class);
        int checkPlanTimeNum = 0;
        for (CheckPlanTimeModel checkPlanTimeModel : checkPlanTimeModelList) {
            checkPlanTimeModel.setTimestart(generaterSwapUtil.dateSwap(checkPlanTimeModel.getTimestart(), "HH:mm"));
            checkPlanTimeModel.setTimeend(generaterSwapUtil.dateSwap(checkPlanTimeModel.getTimeend(), "HH:mm"));
            checkPlanTimeModel.setTimetype(generaterSwapUtil.getDicName(checkPlanTimeModel.getTimetype(), "509339643641104965"));
            checkPlanTimeNum++;
        }
        vo.setCheckPlanTimeList(checkPlanTimeModelList);

        //附表数据转换

//添加到详情表单对象中
        vo.setCreatoruserid(generaterSwapUtil.userSelectValue(vo.getCreatoruserid()));

        vo.setCreatortime(vo.getCreatortime());

        vo.setLastmodifyuserid(generaterSwapUtil.userSelectValue(vo.getLastmodifyuserid()));

        vo.setLastmodifytime(vo.getLastmodifytime());

        vo.setCode(vo.getCode());

        vo.setName(vo.getName());

        vo.setNeeduser(vo.getNeeduser());

        vo.setNeedtime(vo.getNeedtime());

        vo.setErrormax(vo.getErrormax());

        vo.setErrormin(vo.getErrormin());

        vo.setCheckteam(generaterSwapUtil.comSelectValues(vo.getCheckteam(), false));

        vo.setEnabledmark(generaterSwapUtil.switchSelectValue(vo.getEnabledmark(), "开", "关"));

        vo.setDescription(vo.getDescription());

        vo.setFiles(generaterSwapUtil.getFileNameInJson(vo.getFiles()));


        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @param checkPlanForm
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid CheckPlanForm checkPlanForm) throws DataException {
        String b = checkPlanService.checkForm(checkPlanForm, 1);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        }
        UserInfo userInfo = userProvider.get();
        CheckPlanEntity entity = checkPlanService.getInfo(id);
        if (entity != null) {
            checkPlanForm.setLastmodifyuserid(userInfo.getUserId());
            checkPlanForm.setLastmodifytime(DateUtil.getNow());
            CheckPlanEntity subentity = JsonUtil.getJsonToBean(checkPlanForm, CheckPlanEntity.class);
            subentity.setCreatoruserid(entity.getCreatoruserid());
            subentity.setCreatortime(entity.getCreatortime());
            boolean b1 = checkPlanService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }

            QueryWrapper<CheckPlanItemEntity> CheckPlanItemqueryWrapper = new QueryWrapper<>();
            CheckPlanItemqueryWrapper.lambda().eq(CheckPlanItemEntity::getParentid, entity.getId());
            checkPlanItemService.remove(CheckPlanItemqueryWrapper);
            if (checkPlanForm.getCheckplanitemList() != null) {
                List<CheckPlanItemEntity> CheckPlanItemList = JsonUtil.getJsonToList(checkPlanForm.getCheckplanitemList(), CheckPlanItemEntity.class);
                for (CheckPlanItemEntity entitys : CheckPlanItemList) {
                    entitys.setId(RandomUtil.uuId());
                    entitys.setParentid(entity.getId());
                    checkPlanItemService.save(entitys);
                }
            }

            QueryWrapper<CheckPlanTimeEntity> CheckPlanTimequeryWrapper = new QueryWrapper<>();
            CheckPlanTimequeryWrapper.lambda().eq(CheckPlanTimeEntity::getParentid, entity.getId());
            checkPlanTimeService.remove(CheckPlanTimequeryWrapper);
            if (checkPlanForm.getCheckplantimeList() != null) {
                List<CheckPlanTimeEntity> CheckPlanTimeList = JsonUtil.getJsonToList(checkPlanForm.getCheckplantimeList(), CheckPlanTimeEntity.class);
                for (CheckPlanTimeEntity entitys : CheckPlanTimeList) {
                    entitys.setId(RandomUtil.uuId());
                    entitys.setParentid(entity.getId());
                    checkPlanTimeService.save(entitys);
                }
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    @Autowired
    private CheckTaskService checkTaskService;

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        CheckPlanEntity entity = checkPlanService.getInfo(id);
        if (entity != null) {
            // 查询计划下是否有未完成的巡检任务
            List<CheckTaskEntity> list = checkTaskService.getListByPlanCode(entity.getCode());
            if (list.size() > 0) return ActionResult.fail("该巡检计划下有未完成的巡检任务！");
            checkPlanService.delete(entity);

            QueryWrapper<CheckPlanItemEntity> queryWrapperCheckPlanItem = new QueryWrapper<>();
            queryWrapperCheckPlanItem.lambda().eq(CheckPlanItemEntity::getParentid, entity.getId());
            checkPlanItemService.remove(queryWrapperCheckPlanItem);

            QueryWrapper<CheckPlanTimeEntity> queryWrapperCheckPlanTime = new QueryWrapper<>();
            queryWrapperCheckPlanTime.lambda().eq(CheckPlanTimeEntity::getParentid, entity.getId());
            checkPlanTimeService.remove(queryWrapperCheckPlanTime);

            // 删除巡检任务
            QueryWrapper<CheckTaskEntity> taskEntityQueryWrapper = new QueryWrapper<>();
            taskEntityQueryWrapper.lambda().eq(CheckTaskEntity::getPlancode, entity.getCode());
            checkTaskService.remove(taskEntityQueryWrapper);

        }
        return ActionResult.success("删除成功");
    }


}
